package com.lucan.tracking.api;

import android.text.TextUtils;

import com.lucan.tracking.TKMonitor;
import com.lucan.tracking.api.executor.RunnablePriority;
import com.lucan.tracking.api.okhttp.CallBack;
import com.lucan.tracking.api.okhttp.OKHttpUtil;

import java.util.Map;
import java.util.concurrent.ExecutorService;

import okhttp3.Call;
import okhttp3.Response;

/**
 * @author qihailong
 * @date 2018/7/26 上午11:09
 * @description TODO
 */

public class Track {

    private int mPriority;
    private ExecutorService mExecutor;
    private CallBack mCallBack = new CallBack() {
        @Override
        public Object onParseResponse(Call call, Response response) {
            return null;
        }

        @Override
        public void onFailure(Call call, Exception e) {
            e.printStackTrace();
        }

        @Override
        public void onResponse(Object response) {
        }
    };

    public Track(ExecutorService executor, int priority) {
        mExecutor = executor;
        mPriority = priority;
    }

    /**
     * 发送监测url
     *
     * @param url
     * @param params
     * @param post
     */
    public void sendTrack(final String url, final Map<String, String> params, final boolean post) {
        getExecutor().execute(new RunnablePriority(mPriority) {
            @Override
            public void hook() {
                if (post) {
                    OKHttpUtil.okHttpPost(getUrl(url), params, mCallBack);
                } else {
                    OKHttpUtil.okHttpGet(getUrl(url), params, mCallBack);
                }
            }
        });
    }

    private String getUrl(String url) {
        if (TextUtils.isEmpty(url)) {
            return TKMonitor.BASE_URL;
        } else if (url.startsWith("http") || url.startsWith("https")) {
            return url;
        } else {
            return TKMonitor.BASE_URL + url;
        }
    }

    private ExecutorService getExecutor() {
        if (mExecutor == null)
            throw new RuntimeException("Executor is Null");
        return mExecutor;
    }


}
